package zookeeper.demo;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.List;

public class ZKClient2 {
    private String connectString = "localhost:2181";
    private int sessionTimeout = 5000;

    private ZooKeeper zooKeeper = null;

    private String parentNode = "/test";

    private static long index = 1;

    public void getZKClient() throws IOException {
        zooKeeper = new ZooKeeper(connectString, sessionTimeout, event -> {
            System.out.println("get watcher,msg :");
            System.out.println("event : " + event.toString());
            try {
                listen();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public void listen() throws KeeperException, InterruptedException {
        List<String> children = zooKeeper.getChildren(parentNode, true);
        for (String child : children) {
            if (Long.parseLong(child) > index) {
                System.out.println("children:" + child);
                byte[] data = zooKeeper.getData(parentNode + "/" + child, false, null);
                if (data != null) {
                    System.out.println(new String(data));
                }
                index = Long.parseLong(child);
            }

        }
    }

    public void business() throws InterruptedException {
        System.out.println("client is working!");
        Thread.sleep(Long.MAX_VALUE);
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        // 获取连接
        ZKClient2 zkClient = new ZKClient2();
        zkClient.getZKClient();
        // client业务
        zkClient.business();
    }
}
